import { Component, OnInit, OnDestroy } from '@angular/core';
import { ApiService } from '@core/api.service';
import { Router } from '@angular/router';
import { DomSanitizer } from '@angular/platform-browser';
import { LocalStorage } from '@core/local.storage';
import { environment } from '../../../../environments/environment';
import { DatePipe } from '@angular/common';
import { forkJoin } from 'rxjs';
import { NzModalService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
declare const echarts: any;

@Component({
    selector: 'app-control',
    templateUrl: './control.component.html',
    styleUrls: ['./control.component.less']
})

export class ControlComponent implements OnInit, OnDestroy {
    titleName = '';
    alarmAudio = false;
    zhibanList: any = [];
    shigongText: any = [];
    tianqiList: any = [];
    tianqiList_split: any[];
    tqFilterText = '';
    weixiuText: any = [];
    earlyWarningList: any = [];
    iframe: any;
    safeDaysTitle = '';
    kmsafeDays = '';
    dbzzList: any = [];
    dbzzVisible: boolean;
    dbzzRow: any = {};
    ssyjVisible: boolean;
    impWarning: any = {};
    htipsVisible = false;
    dbzzpopVisible = false;
    dbzzType = '';
    ws: WebSocket;
    timeout: any;
    themeClass = 'whitetheme';
    popClass = '';
    tipsPic = './assets/control/tips_white.png';
    kmsat = '<iframe src="/csmis/staht/kmsat.html?' + new Date().getTime() + '&theme=' + this.themeClass + '" frameborder="0" style="width:100%;height:820px;"></iframe>';
    dbzzTitle: string;
    dbzzColor: string;
    zhibanList2: { duan: any[]; dd: any[]; sj: any[]; };
    pageSize = 100;
    pageIndex = 1;
    pageTotal = 0;
    loginInfo: any = {};

    constructor(
        private apiService: ApiService,
        private sanitizer: DomSanitizer,
        private ls: LocalStorage,
        private router: Router,
        private datePipe: DatePipe,
        private http: _HttpClient,
        private modalService: NzModalService
    ) { }

    ngOnInit() {
        if (document.getElementById('controlWrap')) {
            document.getElementById('controlWrap').style.height = document.documentElement.clientHeight + 'px';
        }
        // this.webSocket(environment.wsBase + '/csmis/websocket_alarm/alarm.ws');
        this.webSocket(environment.wsBase + '/csmis/websocket_czjy/czjy.ws');
        this.loginInfo = JSON.parse(this.ls.get('loginInfo'));
        this.alarmQuery(this.loginInfo.N_LEVEL, this.loginInfo.VC_ORG$ID, this.pageIndex, this.pageSize);
        this.iframe = this.sanitizer.bypassSecurityTrustHtml(this.kmsat);
        this.titleName = '铁路局安全生产';
        this.statisticsWork();
        this.dataLoad();
    }
    ngOnDestroy() {
        this.ws = null;
        clearInterval(this.timeout);
    }
    statisticsWork() {
        this.http.get(environment.project + '/skywinStat/monthStatByOrg?monthStr=' + this.datePipe.transform(new Date(), 'yyyy-MM')).subscribe(res => {
            if (!res.code) {
                let data = res.data;
                data.length = data.length - 1; 
                const name = [];
                const finish = [];
                const unfinish = [];
                const option = {
                    color: ['#3ba0cc', '#70d4cd', '#66db87'],
                    legend: { data: [] },
                    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                    grid: { left: '30px', right: '30px', top: '30px', bottom: '0', containLabel: true },
                    xAxis: [{ type: 'category', data: name }],
                    yAxis: [{ type: 'value' }],
                    series: []
                };
                for (const item of data) {
                    name.push(item.orgName);
                    finish.push(item.planFinish);
                    unfinish.push(item.planUnfinish);
                }
                option.legend.data = ['兑现数', '未兑现数'];
                option.series = [
                    { name: '兑现数', type: 'bar', data: finish, label: { normal: { show: true, position: 'top' } } },
                    { name: '未兑现数', type: 'bar', data: unfinish, label: { normal: { show: true, position: 'top' } } }
                ];
                echarts.init(document.getElementById('statistics')).setOption(option);
            }
        });

    }
    alarmQuery(level, orgid, index, size) {
        this.alarmQueryList('1', '1', level, orgid, index, size).subscribe((res: any) => {
            if (res.msg === 'Ok') {
                this.pageTotal = res.count;
                if (res.data.length) {
                    for (const item of res.data) {
                        const data: any = { 'data': '' };
                        data.data = JSON.stringify(item);
                        this.webSocketList('alarmQuery', data);
                    }
                }
            }
        });
    }

    // 获取所有报警列表
    alarmQueryList(czjy, notice, userlevel, org, page, limit) {
        let url = environment.project + '/alarmTab2/query?czjy=' + czjy + '&notice=' + notice + '&org=' + org + '&page=' + page + '&limit=' + limit;
        if (userlevel === 10 || userlevel === 30) {
            url += '&userlevel=' + userlevel;
        }
        return this.http.get(url);
    }
    pageChange(e) {
        this.pageIndex = e;
        this.earlyWarningList = [];
        this.alarmQuery(this.loginInfo.N_LEVEL, this.loginInfo.VC_ORG$ID, this.pageIndex, this.pageSize);
    }
    dataLoad() {
        this.getSafeLoad();
        this.tianqiLoad();
        this.getzbpersonnew(this.datePipe.transform(new Date(), 'yyyy-MM-dd'));
        this.getDbzz();
        this.echartData('todayCracks', 'drsg');
        this.echartData('todayRepair', 'drwx');
        this.vMarq('wtxxScroll', 'li', 38, 20, 3);
    }

    webSocket(url) {
        this.ws = new WebSocket(url);
        this.ws.onopen = () => {
            console.log('已建立连接：' + url);
            // this.timeout = setInterval(() => {
            //     this.ws.send('message of alain!');
            // }, 10000);
        };
        this.ws.onmessage = (data) => {
            console.log('客户端已接到收服务端的数据：' + data);
            this.webSocketList('webSocket', data);
        };
        this.ws.onerror = () => {
            console.log('通信发生错误：' + url);
        };
        this.ws.onclose = () => {
            console.log('已关闭连接：' + url);
        };
    }

    themeChenge(e) {
        this.themeClass = e;
        switch (e) {
            case 'blacktheme':
                this.tipsPic = './assets/control/tips_black.png';
                this.popClass = 'processWrap';
                break;
            case 'whitetheme':
                this.tipsPic = './assets/control/tips_white.png';
                this.popClass = '';
                break;
        }
        this.kmsat = '<iframe src="/csmis/staht/kmsat.html?' + new Date().getTime() + '&theme=' + this.themeClass + '" frameborder="0" style="width:100%;height:820px;"></iframe>';
        this.iframe = this.sanitizer.bypassSecurityTrustHtml(this.kmsat);
    }

    webSocketList(type, _data) {
        let data: any;
        data = JSON.parse(_data.data);
        if (!data.bjid) {
            if (data.keypoint === '1' || data.keypoint === 1) {
                this.alarmAudio = true;
                this.impWarning = data;
                this.showSsyjModal();
            }
            const warning = {
                'stationid': data.stationid,
                'level': data.alarmlevel,
                'name': data.stationname,
                'dev': data.devname,
                'nid': data.nId,
                'devtype': data.devTypeName,
                'devtypeid': data.devType,
                'alarmtext': data.alarmtext,
                'alarmtype': data.alarmtype,
                'alarmdesc': data.alarmdescription,
                'startime': this.datePipe.transform(data.uTime * 1000, 'yyyy-MM-dd')
            };
            if (data.stationname) {
                if (type === 'alarmQuery') {
                    this.earlyWarningList.push(warning);
                } else {
                    this.earlyWarningList.unshift(warning);
                }
            }
        } else {
            // 删除已添加处置流程的记录
            for (let i = 0; i < this.earlyWarningList.length; i++) {
                if (data.bjid == this.earlyWarningList[i].nid) {
                    this.earlyWarningList.splice(i, 1);
                    break;
                }
            }
        }
    }
    // 明细
    detail(type) {
        switch (type) {
            case 'ssyj':
                this.router.navigate(['control/detectalarm']);
                break;
            case 'drsg':
                this.router.navigate(['examconstructionplan_sg/today']);
                break;
            case 'drwx':
                this.router.navigate(['examconstructionplan/today']);
                break;
            case 'dbzz':
                this.dbzzpopVisible = true;
                break;
            case 'cjtj':
                this.router.navigate(['tctj/statistics/org?month=' + this.datePipe.transform(new Date(), 'yyyy-MM') + '&type=org']);
                break;
        }
    }
    dbzzpopOk() {
        this.dbzzpopVisible = false;
    }
    // 图示
    picview(type, name) {
        switch (type) {
            case 'ssyj':
                this.iframe = this.sanitizer.bypassSecurityTrustHtml(this.kmsat);
                break;
            case 'drsg':
                this.svgConstruct().subscribe((res: any) => {
                    if (!res.data.pageList.length) {
                        this.iframe = this.sanitizer.bypassSecurityTrustHtml(this.kmsat);
                    } else {
                        const newres: any = [];
                        for (const item of res.data.pageList) {
                            if (item.STATUS == name) {
                                newres.push(item);
                            }
                        }
                        window.frames[0].postMessage({ 'type': 'drsg', 'name': name, 'data': newres }, window.location.protocol + '//' + window.location.host);
                    }
                });
                break;
            case 'drwx':
                this.findstadayworkstat().subscribe((res: any) => {
                    if (!res.length) {
                        this.iframe = this.sanitizer.bypassSecurityTrustHtml(this.kmsat);
                    } else {
                        window.frames[0].postMessage({ 'type': 'drwx', 'name': name, 'data': res }, window.location.protocol + '//' + window.location.host);
                    }
                });
                break;
        }
    }

    // 当日施工明细
    svgConstruct() {
        const url = environment.apiBase + '/csmis/peihesg/phtconstructsgxt/findrsgConstruct.jwt';
        return this.http.get(url);
    }
    // 当日维修明细
    findstadayworkstat() {
        const url = environment.apiBase + '/csmis/prod/findstadayworkstat.jwt';
        return this.http.get(url);
    }
    // 预警详情
    yujingZoom(data) {
        if (data.level === 1) {
            this.alarmAudio = false;
        }
        let desc = '';
        !data.alarmdesc ? desc = '' : desc = data.alarmdesc;

        this.router.navigate(['control/diagnose'], {
            queryParams: {
                'NID': data.nid,
                'STATIONID': data.stationid,
                'STATIONNAME': encodeURI(encodeURI(data.name)),
                'ALARMLEVEL': data.level,
                'ALARMTEXT': encodeURI(encodeURI(data.alarmtext)),
                'ALARMTYPE': data.alarmtype,
                'DEVNAME': encodeURI(encodeURI(data.dev)),
                'DEVTYPE': data.devtype,
                'DEVTYPEID': data.devtypeid,
                'TIME': data.startime,
                'ALARMDESCRIPTION': desc
            }
        });
    }
    // 安全生产天数
    getSafeLoad() {
        this.getSafeDays().subscribe((res: any) => {
            for (const item of res.pageList) {
                if (item.N_LEVEL == 50) {
                    this.safeDaysTitle = item.DAYS;
                } else if (item.N_LEVEL == 80) {
                    this.kmsafeDays = item.DAYS;
                }
            }
        });
    }
    // 安全生产天数
    getSafeDays() {
        const url = environment.apiBase + '/csmis/publicpro/getsafedays.jwt';
        return this.http.get(url);
    }
    // 天气
    tianqiLoad() {
        this.findweatherdate(this.datePipe.transform(new Date(), 'yyyy-MM-dd')).subscribe((res: any) => {
            if (res.length) {
                let data = res[0].vcWeathermatter;
                if (data.substring(0, 1) == '"') {
                    data = data.substring(1, data.length);
                }
                if (data.substring(data.length - 1, data.length) == '"') {
                    data = data.substring(0, data.length - 1);
                }
                data = data.replace(/ /g, '');
                if (data.indexOf(';') == -1) {
                    for (const item of data.split('；')) {
                        this.tianqiList.push({ 'name': item });
                    }
                } else {
                    for (const item of data.split('；')) {
                        this.tianqiList.push({ 'name': item });
                    }
                }
            }
        });
    }

    // 获取办公网天气
    findweatherdate(date) {
        const url = environment.apiBase + '/csmis/sys/systweather/findweatherdate.jwt?dates=' + date;
        return this.http.get(url);
    }
    // 值班人员
    getzbpersonnew(time) {
        this.getzbperson(time).subscribe((res: any) => {
            if (res.pageList.length) {
                for (const item of res.pageList) {
                    this.zhibanList.push({
                        'dep': !item.DEP_ARRANGE ? '' : '段安排：' + item.DEP_ARRANGE,
                        'dis': !item.DIS_ARRANGE ? '' : '调度安排：' + item.DIS_ARRANGE,
                        'dri': !item.DRIVER ? '' : '司机：' + item.DRIVER
                    });
                }
            }
        });
    }

    // 值班人员(首页)
    getzbperson(time) {
        const url = environment.apiBase + '/csmis/publicpro/getzbpersonnew.jwt?begindate=' + time;
        return this.http.get(url);
    }
    // 督办追踪
    getDbzz() {
        const today = new Date();
        const yestodayDate = today.getDate() - 1;
        const yestoday = today.setDate(yestodayDate);
        this.apiService.handover_dispatcher('ryap', { 'DUTY_DATE': this.datePipe.transform(yestoday, 'yyyy-MM-dd') }, 'query').subscribe((res: any) => {
            if (res.type === "success") {
                const data = res.response.data;
                let dutyId;
                if (data.length) {
                    dutyId = data[0].ID + '';
                    const ob1 = this.apiService.handover_dispatcher('scxx_zgs_dzz', {
                        DUTY_ID: dutyId,
                        TYPE: '0'
                    }, 'query');
                    const ob2 = this.apiService.handover_dispatcher('scxx_zgs_dzz', {
                        DUTY_ID: dutyId,
                        TYPE: '1'
                    }, 'query');
                    forkJoin(ob1, ob2).subscribe(resArr => {
                        let data2 = [];
                        resArr.forEach((res2: any) => {
                            const _data = res2.response.data;
                            data2 = [...data, ..._data];
                        });
                        this.dbzzList = data;
                    });
                }
            }
        });
    }

    showDbzzModal(type, index) {
        this.dbzzType = type;
        switch (type) {
            case 'list':
                this.dbzzpopVisible = false;
                break;
        }
        this.dbzzVisible = true;
        this.dbzzRow = this.dbzzList[index];
        let finishState = '';
        if (this.dbzzRow.FINISHDATE) {
            const days = (+new Date() - +new Date(this.dbzzRow.FINISHDATE)) / 1000 / 3600 / 24;
            if (days > 0) {
                finishState = `(已超期)`;
                this.dbzzColor = `red`;
            } else if (days <= 0 && days >= -3) {
                finishState = `(即将超期)`;
                this.dbzzColor = `#e8c214`;
            }
        }
        this.dbzzTitle = `${finishState}`;
    }

    hideDbzzModal() {
        this.dbzzVisible = false;
        switch (this.dbzzType) {
            case 'list':
                this.dbzzpopVisible = true;
                break;
        }
    }

    showSsyjModal() {
        this.ssyjVisible = true;
    }

    hideSsyjModal() {
        this.ssyjVisible = false;
        this.alarmAudio = false;
    }

    echartData(id, type) {
        const wks = '#f2d47f'; // 未开始
        const jxz = '#b5a0f8'; // 进行中
        const ywc = '#52eca5'; // 已完成
        const wksColor = '#d9ac2a';
        const jxzColor = '#7551ea';
        const ywcColor = '#20ce7e';
        const data = [
            { 'name': '未开始', 'value': 0, itemStyle: { normal: { color: wks } } },
            { 'name': '进行中', 'value': 0, itemStyle: { normal: { color: jxz } } },
            { 'name': '已完成', 'value': 0, itemStyle: { normal: { color: ywc } } },
        ];

        switch (type) {
            case 'drsg':
                this.findnowdaysg().subscribe((res: any) => {
                    for (const item of res) {
                        switch (item.GQSTATUS) {
                            case '未开始':
                                data[0].value = item.NUMS;
                                break;
                            case '进行中':
                                data[1].value = item.NUMS;
                                break;
                            case '已完成':
                                data[2].value = item.NUMS;
                                break;
                        }
                    }
                    this.shigongText = data;
                    this.shigongText[0].color = wksColor;
                    this.shigongText[1].color = jxzColor;
                    this.shigongText[2].color = ywcColor;
                    this.echartLoad(id, type, data);
                });
                break;
            case 'drwx':
                this.getstadaywork().subscribe((res: any) => {
                    for (const item of res) {
                        switch (item.VC_STATUS) {
                            case 0: // 未开始
                                data[0].value = item.NUMS;
                                break;
                            case 1: // 进行中
                                data[1].value = item.NUMS;
                                break;
                            case 2: // 已完成
                                data[2].value = item.NUMS;
                                break;
                        }
                    }
                    this.weixiuText = data;
                    this.weixiuText[0].color = wksColor;
                    this.weixiuText[1].color = jxzColor;
                    this.weixiuText[2].color = ywcColor;
                    this.echartLoad(id, type, data);
                });
                break;
        }
    }

    // 当日维修
    getstadaywork() {
        const url = environment.apiBase + '/csmis/prod/getstadaywork.jwt';
        return this.http.get(url);
    }
    // 当日施工
    findnowdaysg() {
        const url = environment.apiBase + '/csmis/peihe/findnowdaysg.jwt';
        return this.http.get(url);
    }
    echartLoad(id, type, data) {
        echarts.init(document.getElementById(id)).setOption({
            tooltip: {
                trigger: 'item',
                formatter: '{b} : {c} ({d}%)'
            },
            series: [
                {
                    type: 'pie',
                    radius: '85%',
                    center: ['50%', '50%'],
                    selectedMode: 'single',
                    avoidLabelOverlap: false,
                    label: {
                        normal: {
                            show: false,
                            position: 'center'
                        }
                    },
                    grid: {
                        'left': 0,
                        'right': 0,
                        'top': 0,
                        'bottom': 0
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data
                }
            ]
        }, true);
        echarts.init(document.getElementById(id)).on('click', (param) => {

            switch (type) {
                case 'drsg':
                    this.picview(type, param.name);
                    break;
                case 'drwx':
                    let status: any;
                    switch (param.name) {
                        case '未开始':
                            status = 0;
                            break;
                        case '进行中':
                            status = 1;
                            break;
                        case '已完成':
                            status = 2;
                            break;
                    }
                    this.picview(type, status);
                    break;
            }
        });
    }
    htips() {
        this.htipsVisible = true;
    }
    htipsOk() {
        this.htipsVisible = false;
    }
    vMarq(id, tag, heigh, speed, delay) {
        const move = function () {
            const me = this;
            me.EL = document.getElementById(id);
            me.PA = 0;
            me.TI = null;
            me.LH = heigh;
            me.SP = speed;
            me.DY = delay;
            me.exec = () => {
                if (me.PA) return;
                me.EL.scrollTop += 2;
                if (me.EL.scrollTop % me.LH <= 1) {
                    clearInterval(me.TI);
                    me.EL.appendChild(me.EL.getElementsByTagName(tag)[0]);
                    me.EL.scrollTop = 0;
                    setTimeout(me.start, me.DY * 1000);
                }
            };
            me.start = () => {
                if (me.EL.scrollHeight - me.EL.offsetHeight >= me.LH) me.TI = setInterval(me.exec, me.SP);
            };
            me.EL.onmouseover = () => { me.PA = 1; };
            me.EL.onmouseout = () => { me.PA = 0; };
            setTimeout(me.start, me.DY * 1000);
        };
        return new move();
    }

    splitTq(row) {
        return row.split(/：|，|:|,/);
    }

    tqFilter(v) {
        const list = [];
        this.tianqiList.forEach(el => {
            if (el.name && el.name.includes(v)) {
                list.push(this.splitTq(el.name));
            }
        });
        this.tianqiList_split = list;
    }

    showTq(content) {
        this.tianqiList_split = [];
        this.tianqiList.forEach(el => {
            this.tianqiList_split.push(this.splitTq(el.name));
        });
        this.modalService.info({
            nzTitle: `<b style="font-size:20px">天气信息</b>`,
            nzWidth: '600',
            nzContent: content,
        });
    }
    showLd(content) {
        this.zhibanList2 = {
            duan: [],
            dd: [],
            sj: [],
        };
        this.zhibanList.forEach(row => {
            const duan = row.dep.split('：')[1];
            const dd = row.dis.split('：')[1];
            const sj = row.dri.split('：')[1];
            this.zhibanList2.duan.push(duan);
            this.zhibanList2.dd.push(dd);
            this.zhibanList2.sj.push(sj);
        });
        this.modalService.info({
            nzTitle: `<b style="font-size:20px">值班领导</b>`,
            nzWidth: '600',
            nzContent: content,
        });
    }
}
